package com.csc.banking.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.csc.banking.dao.CustomerDao;
import com.csc.banking.model.Customer;

public class UserAccountDao implements UserDetailsService
{
	@Autowired	
	private CustomerDao customerDao;
	
	public CustomerDao getCustomerDao() 
	{
		return customerDao;
	}

	public void setCustomerDao(CustomerDao customerDao) 
	{
		this.customerDao = customerDao;
	}

	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException 
	{
		
		Customer cus=customerDao.getCustomer(username);
		if(cus==null){
			System.out.println("UserName: "+username+" not found");
			throw new UsernameNotFoundException("UserName: "+username+" not found");
		}		
	//	System.out.println("Find :"+cus.getUsername()+":"+cus.getPassword());		
		UserDetails user = new User(cus.getUserName(), cus.getPassword(), 
				true, true, true, !cus.getIsLock(),getAuthorities(0));
		return user;
	}

	public Collection<GrantedAuthority> getAuthorities(Integer access) 
	{
	    List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);

	    if (access.compareTo(1) == 0) 
	    {//assume 1 as admin
	        authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
	    }
	    else{//assume 0 as user
	        authList.add(new SimpleGrantedAuthority("ROLE_USER"));
	    }
	    return authList;
	}

}
